<template>
  <div class="admin-orders-page">
    <div class="header-section">
      <h1 class="page-title">订单管理</h1>
      <div class="search-filter-bar">
        <!-- 搜索框和按钮组合 -->
        <div class="search-group">
          <input
              v-model="searchQuery"
              type="text"
              placeholder="搜索订单ID或用户名..."
              class="search-input"
              @change="handleSearch"
          />
          <!-- 美化后的搜索按钮 -->
          <button class="search-btn" @click="handleSearch">
            <i class="fas fa-search"></i>
            <span>搜索</span>
          </button>
        </div>

        <select v-model="activeStatus" class="status-select" @change="handleFilter">
          <option value="all">所有状态</option>
          <option value="1">待确认</option>
          <option value="2">进行中</option>
          <option value="3">已完成</option>
          <option value="4">已取消</option>
        </select>
      </div>
    </div>

    <div v-if="errorMessage" class="error-message">
      <i class="fas fa-exclamation-circle"></i>
      <span>{{ errorMessage }}</span>
    </div>

    <div class="orders-table-container">
      <table class="orders-table">
        <thead>
        <tr>
          <th>订单ID</th>
          <th>订单编号</th>
          <th>用户名</th>
          <th>商品名</th>
          <th>数量</th>
          <th>积分</th>
          <th>创建日期</th>
          <th>状态</th>
          <th style="width: 200px;">操作</th>
        </tr>
        </thead>
        <tbody v-if="loading">
        <tr>
          <td colspan="9" class="loading">
            <i class="fas fa-spinner fa-spin"></i>
            <p>正在加载订单数据...</p>
          </td>
        </tr>
        </tbody>
        <tbody v-else-if="paginatedOrders.length > 0">
        <tr v-for="order in paginatedOrders" :key="order.orderId">
          <td class="order-id">{{ order.orderId }}</td>
          <td>{{ order.orderNumber }}</td>
          <td>{{ order.users.nickname }}</td>
          <td>{{ order.mallProducts.name }}</td>
          <td>{{ order.quantity }}</td>
          <td class="points-cell">{{ order.pointsAmount }}</td>
          <td>{{ formatDate(order.createdAt) }}</td>
          <td>
              <span class="status-badge" :class="'status-' + order.status">
                {{ getStatusName(order.status) }}
              </span>
          </td>
          <td>
            <button class="action-btn btn-view" @click="showDetailsModal(order)">
              查看详情
            </button>
            <button class="action-btn btn-edit" @click="showStatusModal(order)">
              修改状态
            </button>
          </td>
        </tr>
        </tbody>
        <tbody v-else>
        <tr>
          <td colspan="9" class="empty-state">
            <i class="fas fa-box-open empty-icon"></i>
            <p>暂无相关订单</p>
          </td>
        </tr>
        </tbody>
      </table>
    </div>
    <el-pagination background class="pagination-container"
                   :total="tableData.total" :current-page="tableData.page"
                   :page-size="tableData.limit" @current-change="jump"
                   layout="total,prev,pager,next,jumper"></el-pagination>
    <AppModal :visible="detailsModalVisible" title="订单详情" @update:visible="detailsModalVisible = $event">
      <div v-if="selectedOrderDetails" class="modal-content-details">
        <p><strong>订单ID:</strong> {{ selectedOrderDetails.orderId }}</p>
        <p><strong>订单编号:</strong> {{ selectedOrderDetails.orderNumber }}</p>
        <p><strong>用户昵称:</strong> {{ selectedOrderDetails.users.nickname }}</p>
        <p><strong>商品名称:</strong> {{ selectedOrderDetails.mallProducts.name }}</p>
        <p><strong>数量:</strong> {{ selectedOrderDetails.quantity }}</p>
        <p><strong>积分:</strong> {{ selectedOrderDetails.pointsAmount }}</p>
        <p><strong>配送信息:</strong> {{ selectedOrderDetails.shippingInfo }}</p>
        <p><strong>订单状态:</strong> {{ getStatusName(selectedOrderDetails.status) }}</p>
        <p><strong>创建日期:</strong> {{ formatDate(selectedOrderDetails.createdAt) }}</p>
        <p v-if="selectedOrderDetails.updatedAt">
          <strong>更新日期:</strong> {{ formatDate(selectedOrderDetails.updatedAt) }}
        </p>
      </div>
    </AppModal>

    <AppModal :visible="statusModalVisible" title="修改订单状态" @update:visible="statusModalVisible = $event" @confirm="updateOrderStatus">
      <div class="modal-content-status">
        <p>正在为订单 <strong>{{ selectedOrder?.orderNumber || selectedOrder?.orderId }}</strong> 修改状态。</p>
        <div class="form-group">
          <label for="status-change">选择新状态:</label>
          <select id="status-change" v-model="newStatus" class="form-select">
            <option value="1">待确认</option>
            <option value="2">进行中</option>
            <option value="3">已完成</option>
            <option value="4">已取消</option>
          </select>
        </div>
      </div>
    </AppModal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import AppModal from '../components/AppModal.vue'

// 状态管理
//存储从后端api获取的订单列表
const ordersData = ref([])
//控制订单详情模态框的显示和隐藏
const detailsModalVisible = ref(false)
//控制修改状态模态框的显示和隐藏
const statusModalVisible = ref(false)
//存储用户当前选中的订单对象
const selectedOrder = ref(null)
//存储选中订单的详细信息
const selectedOrderDetails = ref(null)
//存储用户选择的新状态值
const newStatus = ref('')
//存储搜索输入框的内容
const searchQuery = ref('')
//存储当前选中的筛选状态
const activeStatus = ref('all')
//控制加载状态的显示
const loading = ref(false)
//错误信息的提示
const errorMessage = ref('')

// 分页数据 - 使用reactive对象
const tableData = reactive({
  total: 0,
  page: 1,
  limit: 5
})

// 状态名称映射
const statusMap = {
  '1': '待确认',
  '2': '进行中',
  '3': '已完成',
  '4': '已取消',
}

// 工具函数
const getStatusName = (status) => statusMap[status] || status
const formatDate = (dateString) => {
  if (!dateString) return 'N/A'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: 'numeric',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}
//onMounted挂载
// 从后端获取订单数据
const fetchOrders = async () => {
  loading.value = true
  errorMessage.value = ''

  try {
    // 构建查询参数
    const params = new URLSearchParams({
      start: (tableData.page - 1) * tableData.limit,
      limit: tableData.limit,
    })

    if (searchQuery.value) {
      params.append('keyword', searchQuery.value)
    }

    if (activeStatus.value !== 'all') {
      params.append('status', activeStatus.value)
    }
    //fetch() 是浏览器内置的用于发起网络请求的 API，返回一个 Promise 对象，所以这里使用 await 关键字来等待请求完成。
    const response = await fetch(`/api/mallOrders/orders?${params}`)

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result = await response.json()

    if (result.code === 200) {
      ordersData.value = result.data.data
      // 更新总数
      tableData.total = result.data.total || result.data.length
    } else {
      throw new Error(result.msg || '获取订单数据失败')
    }
  } catch (error) {
    console.error('获取订单数据出错:', error)
    errorMessage.value = `获取订单数据失败: ${error.message}`
  } finally {
    loading.value = false
  }
}

// 分页跳转
const jump = (page) => {
  tableData.page = page
  fetchOrders()
}

// 获取当前页的数据
const paginatedOrders = computed(() => {
  return ordersData.value
})

// 事件处理
const handleSearch = () => {
  tableData.page = 1
  fetchOrders()
}

const handleFilter = () => {
  tableData.page = 1
  fetchOrders()
}

const showDetailsModal = (order) => {
  selectedOrderDetails.value = order
  detailsModalVisible.value = true
}

const showStatusModal = (order) => {
  selectedOrder.value = order
  newStatus.value = order.status.toString() // 预设当前状态
  statusModalVisible.value = true
}

const updateOrderStatus = async () => {
  if (selectedOrder.value && newStatus.value) {
    try {
      // 在实际应用中，这里应该调用API发送更新请求
      const response = await fetch(`/api/mallOrders/updateStatus/${selectedOrder.value.orderId}?status=`+parseInt(newStatus.value), {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        }
        // ,
        // body: JSON.stringify({
        //   status: parseInt(newStatus.value)
        // })
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()

      if (result.code === 200) {
        // 更新本地数据
        const orderToUpdate = ordersData.value.find(o => o.orderId === selectedOrder.value.orderId)
        if (orderToUpdate) {
          orderToUpdate.status = parseInt(newStatus.value)
        }
        console.log(`订单 ${orderToUpdate.orderId} 的状态已更新为 ${newStatus.value}`)
      } else {
        throw new Error(result.msg || '更新订单状态失败')
      }
    } catch (error) {
      console.error('更新订单状态出错:', error)
      errorMessage.value = `更新订单状态失败: ${error.message}`
    } finally {
      statusModalVisible.value = false
    }
  }
}

// 生命周期钩子
onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
/* 页面布局 */
.admin-orders-page {
  padding: 30px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.search-filter-bar {
  display: flex;
  gap: 15px;
}

.search-input,
.status-select {
  padding: 10px 15px;
  border: 1px solid #e0e6ed;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s;
  background-color: white;
}

.search-input:focus,
.status-select:focus {
  outline: none;
  border-color: #4e54c8;
  box-shadow: 0 0 0 3px rgba(78, 84, 200, 0.1);
}

.orders-table-container {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.orders-table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

.orders-table th,
.orders-table td {
  padding: 15px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
  font-size: 14px;
}

.orders-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #555;
  text-transform: uppercase;
}

.orders-table td {
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.order-id, .points-cell {
  font-family: monospace;
}

.status-badge {
  padding: 5px 10px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  color: white;
  white-space: nowrap;
}

.status-1 {
  background-color: #f39c12;
}
.status-2 {
  background-color: #3498db;
}
.status-3 {
  background-color: #27ae60;
}
.status-4 {
  background-color: #e74c3c;
}

.action-btn {
  padding: 8px 12px;
  border-radius: 6px;
  border: none;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s;
  margin-right: 8px;
  font-weight: 500;
}

.btn-view {
  background-color: #5d67e8;
  color: white;
}

.btn-view:hover {
  background-color: #4e54c8;
}

.btn-edit {
  background-color: #f1f3f5;
  color: #555;
}

.btn-edit:hover {
  background-color: #e0e6ed;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #999;
}

.empty-icon {
  font-size: 40px;
  margin-bottom: 10px;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #666;
}

.error-message {
  background-color: #ffe6e6;
  color: #d32f2f;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.modal-content-details p {
  margin-bottom: 10px;
  font-size: 15px;
  color: #444;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  font-weight: 500;
  margin-bottom: 5px;
  color: #555;
}

.form-select {
  width: 100%;
  padding: 10px;
  border-radius: 6px;
  border: 1px solid #ccc;
}

/* 分页容器样式 */
/* 分页容器样式：增加上下间距，优化与表格的距离 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin: 25px 0;  /* 上下各25px间距，比原来的20px更协调 */
}

/* 搜索框和按钮组合容器 */
.search-group {
  display: flex;
  align-items: center;
  gap: 0; /* 消除间距使边框合并 */
}

/* 搜索输入框调整 */
.search-input {
  border-radius: 8px 0 0 8px; /* 左侧圆角 */
  margin-right: 0; /* 移除原有右边距 */
  width: 240px;
}

/* 美化的搜索按钮样式 */
.search-btn {
  padding: 10px 18px;
  border: none;
  border-radius: 0 8px 8px 0; /* 右侧圆角，与输入框呼应 */
  background-color: #5d67e8; /* 与查看按钮同色系 */
  color: white;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 悬停效果 */
.search-btn:hover {
  background-color: #4a54d4;
  transform: translateY(-1px);
  box-shadow: 0 3px 8px rgba(93, 103, 232, 0.3);
}

/* 点击效果 */
.search-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(93, 103, 232, 0.2);
}

/* 图标样式 */
.search-btn i {
  font-size: 15px;
}

</style>